<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-hk">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="转载请注明出处 http://averson.oschina.io/blog/2017/02/14/Dagger2 浅析
QA
什么是 IOC ? 为什么使用 IOC ?
为什么使用 Dagger2 ?
Dagger2 有哪些基本操作符?
Dagger2 的基本使用
为什么使用懒加载?
处理子类注入问题
深入 Component
关于 Scope 的理解
参考文献">
<meta property="og:type" content="article">
<meta property="og:title" content="Dagger2 浅析">
<meta property="og:url" content="http://jocens.oschina.io/blog/2017/02/14/Dagger2 浅析/index.html">
<meta property="og:site_name" content="Averson">
<meta property="og:description" content="转载请注明出处 http://averson.oschina.io/blog/2017/02/14/Dagger2 浅析
QA
什么是 IOC ? 为什么使用 IOC ?
为什么使用 Dagger2 ?
Dagger2 有哪些基本操作符?
Dagger2 的基本使用
为什么使用懒加载?
处理子类注入问题
深入 Component
关于 Scope 的理解
参考文献">
<meta property="og:image" content="https://git.oschina.net/averson/Source/raw/master/dagger-1.png">
<meta property="og:image" content="https://git.oschina.net/averson/Source/raw/master/dagger-2.png">
<meta property="og:image" content="https://git.oschina.net/averson/Source/raw/master/dagger-3.png">
<meta property="og:image" content="https://git.oschina.net/averson/Source/raw/master/dagger-4.png">
<meta property="og:updated_time" content="2017-02-20T02:05:30.888Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Dagger2 浅析">
<meta name="twitter:description" content="转载请注明出处 http://averson.oschina.io/blog/2017/02/14/Dagger2 浅析
QA
什么是 IOC ? 为什么使用 IOC ?
为什么使用 Dagger2 ?
Dagger2 有哪些基本操作符?
Dagger2 的基本使用
为什么使用懒加载?
处理子类注入问题
深入 Component
关于 Scope 的理解
参考文献">
<meta name="twitter:image" content="https://git.oschina.net/averson/Source/raw/master/dagger-1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://jocens.oschina.io/blog/2017/02/14/Dagger2 浅析/"/>





  <title> Dagger2 浅析 | Averson </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-hk">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/blog/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Averson</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle"></p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首頁
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            歸檔
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            標籤
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://jocens.oschina.io/blog/blog/2017/02/14/Dagger2 浅析/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Averson">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/blog/images/avatar.gif">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Averson">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="Averson" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Dagger2 浅析
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">發表於</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-02-14T16:00:50+08:00">
                2017-02-14
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2017/02/14/Dagger2 浅析/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/02/14/Dagger2 浅析/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>转载请注明出处 <a href="http://averson.oschina.io/blog/2017/02/14/Dagger2%20%E6%B5%85%E6%9E%90/" target="_blank" rel="external">http://averson.oschina.io/blog/2017/02/14/Dagger2 浅析</a></p>
<h2 id="QA"><a href="#QA" class="headerlink" title="QA"></a>QA</h2><ul>
<li>什么是 <code>IOC</code> ? 为什么使用 <code>IOC</code> ?</li>
<li>为什么使用 <code>Dagger2</code> ?</li>
<li><code>Dagger2</code> 有哪些基本操作符?</li>
<li><code>Dagger2</code> 的基本使用</li>
<li>为什么使用懒加载?</li>
<li>处理子类注入问题</li>
<li>深入 <code>Component</code></li>
<li>关于 <code>Scope</code> 的理解</li>
<li>参考文献</li>
</ul>
<a id="more"></a>
<h2 id="什么是-IOC-为什么使用-IOC"><a href="#什么是-IOC-为什么使用-IOC" class="headerlink" title="什么是 IOC ? 为什么使用 IOC ?"></a>什么是 IOC ? 为什么使用 IOC ?</h2><p><code>IOC</code> ( Inversion of Control ) 称为控制反转, 减低计算机代码之间的耦合度, 最常见的方式叫做 “<code>依赖注入</code>“ ( Denpendency Injection ), 另一种是 “<code>依赖查找</code>“ ( Dependency Loopkup ). 简而言之就是对象创建的时候用一种方式将所有需要的依赖实体的引用传递给该对象, 这种方式称之为 “<code>依赖被注入到对象中</code>“</p>
<p>使用 <code>IOC</code> 的好处可以解耦, 且依赖的是抽象, 拓展性更好, 测试更加方便.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Component</span> </span>&#123;</div><div class="line"></div><div class="line">    Dependency mDependency;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Component</span><span class="params">()</span> </span>&#123;&#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">// constructor inject</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Component</span><span class="params">(Dependency dependency)</span> </span>&#123;</div><div class="line">      mDependency = dependency;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">// setter inject</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">injectDependency</span><span class="params">(Dependency dependency)</span> </span>&#123;</div><div class="line">      mDependency = dependency;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">      mDependency.doAnyThing();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="class"><span class="keyword">interface</span> <span class="title">Dependency</span> </span>&#123;</div><div class="line">    <span class="function">String <span class="title">doAnyThing</span><span class="params">()</span></span>;</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="comment">// 2. 当代码逻辑变动的时候, 只需要修改依赖抽象接口的实现方法, 而不用大改业务逻辑层的代码.</span></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SampleDependency</span> <span class="keyword">implements</span> <span class="title">Dependency</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span> <span class="function"><span class="keyword">public</span> String <span class="title">doAnyThing</span><span class="params">()</span> </span>&#123;</div><div class="line">      <span class="keyword">return</span> <span class="string">"fetch data from remote server"</span>;</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    <span class="comment">// 1. 依赖的注入和配置独立于组件之外</span></div><div class="line">    Dependency dependency = <span class="keyword">new</span> SampleDependency();</div><div class="line">    Component component = <span class="keyword">new</span> Component(dependency);</div><div class="line">    component.run();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 3. 便于测试</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="keyword">private</span> Component  mComponent;</div><div class="line">  <span class="keyword">private</span> Dependency mDependencyMock;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="meta">@Before</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;</div><div class="line">    mDependencyMock = Mockito.mock(Dependency.class);</div><div class="line">    mComponent = <span class="keyword">new</span> Component(mDependencyMock);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">// 验证 Component 中的 run 方法就是 验证 Dependency.doAnyThing() 是否执行</span></div><div class="line">  <span class="meta">@Test</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testRun</span><span class="params">()</span> </span>&#123;</div><div class="line">    mComponent.run();</div><div class="line">    Mockito.verify(mDependencyMock).doAnyThing();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="为什么使用-Dagger2"><a href="#为什么使用-Dagger2" class="headerlink" title="为什么使用 Dagger2 ?"></a>为什么使用 <code>Dagger2</code> ?</h2><p>随着代码的增加, 依赖会越来越复杂. 我们会为了构建一个完整的对象不断有序的一步步构建所有依赖并注入, 随之而来的问题就是代码量庞大且臃肿. 所以 <code>Dagger2</code> 可以简化这些步骤. 它能让依赖有条理的显示在 <code>Module</code> 中和使用 <code>Component</code> 可控的注入依赖到需要依赖的地方且有助于进行单元测试.</p>
<blockquote>
<p>一个简单的例子, 仅做两者的一个大概描述</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">IOCActivity</span> <span class="keyword">extends</span> <span class="title">Activity</span> </span>&#123;</div><div class="line"></div><div class="line">  HomePresenter mPresenter;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">initPresenter</span><span class="params">()</span> </span>&#123;</div><div class="line">    LocalDataSource local = <span class="keyword">new</span> LocalDataSource(getApplication());</div><div class="line">    RemoteDataSource remote = <span class="keyword">new</span> RemoteDataSource();</div><div class="line">    DataRepository repository = <span class="keyword">new</span> DataRepository(local, remote);</div><div class="line">    mPresenter = <span class="keyword">new</span> HomePresenter(<span class="keyword">this</span>, repository);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">DaggerActivity</span> <span class="keyword">extends</span> <span class="title">Activity</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Inject</span> HomePresenter mPresenter;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">initPresenter</span><span class="params">()</span> </span>&#123;</div><div class="line">    DaggerHomeComponent.builder()</div><div class="line">      .addHomePresenterModule(<span class="keyword">new</span> HomePresenterModule(<span class="keyword">this</span>))</div><div class="line">      .dataRepositoryComponent(getApplication().getDataRepositoryComponent().build())</div><div class="line">      .inject(<span class="keyword">this</span>);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Dagger2-有哪些基本操作符"><a href="#Dagger2-有哪些基本操作符" class="headerlink" title="Dagger2 有哪些基本操作符?"></a>Dagger2 有哪些基本操作符?</h2><p>基本操作符:</p>
<ul>
<li><code>@Module</code> 提供依赖的源</li>
<li><code>@Providers</code> 标识依赖是否对外暴露</li>
<li><code>@Component</code> 注入器即充当 <code>@Inejct</code> 和 <code>@Module</code> 的桥梁</li>
<li><code>@Qualifier</code> 区分抽象的实现</li>
<li><code>@Scope</code> 范围限定( 实际取决于 <code>inject</code> 的位置和 <code>component dependency</code> 的正确设置 )</li>
</ul>
<h2 id="Dagger2-基本使用"><a href="#Dagger2-基本使用" class="headerlink" title="Dagger2 基本使用"></a>Dagger2 基本使用</h2><p>Android Studio 添加 <code>Dagger2</code> 支持请看<a href="https://github.com/google/dagger#android-gradle" target="_blank" rel="external">官网说明</a></p>
<blockquote>
<p>基本使用, <code>DaggerXXXComponent</code> 由 <code>Dagger</code> 生成, 你需要先编译当前项目.</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 依赖源提供</span></div><div class="line"><span class="meta">@Module</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LuckyModule</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Provides</span> <span class="function">String <span class="title">provideLuckyLanguage</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="string">"Good Lucky"</span>;</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="meta">@Provides</span> <span class="function">Integer <span class="title">provideLuckyNumber</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> Integer.valueOf(<span class="number">7</span>);</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Component</span>(modules = LuckyModule.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">LuckyComponent</span> </span>&#123;</div><div class="line">  <span class="comment">// initialization inject @Inject mark dependencies.</span></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">inject</span><span class="params">(LuckyTest test)</span></span>;</div><div class="line"></div><div class="line">  <span class="comment">// if don't need separate inject remove below code</span></div><div class="line">  <span class="function">String  <span class="title">luckyLanguage</span><span class="params">()</span></span>;</div><div class="line">  <span class="function">Integer <span class="title">luckyNumber</span><span class="params">()</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LuckyTest</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="comment">// 1. 标识 (@Inject) 初始化就需要注入的依赖让 Dagger 提供注入, 反之不需要标识.</span></div><div class="line">  <span class="meta">@Inject</span> Integer mLuckyNumber;</div><div class="line">  <span class="meta">@Inject</span> String  mLuckyLanguage;</div><div class="line">  LuckyComponent  mLuckyComponent;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="comment">// 2. 初始化注入器</span></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">initInjector</span><span class="params">()</span> </span>&#123;</div><div class="line">    mLuckyComponent = DaggerLuckyComponent.builder()</div><div class="line">      .luckyModule(<span class="keyword">new</span> LuckyModule())</div><div class="line">      .build();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="comment">// 3-1. 整体注入即: 为当前类所有声明 @Inject 的依赖进行注入</span></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">overallInject</span><span class="params">()</span> </span>&#123;</div><div class="line">    mLuckyComponent.inject(<span class="keyword">this</span>);</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="comment">// 3-2. 单独注入即: 不需要一开始就注入依赖用到才手动注入依赖</span></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">separateInject</span><span class="params">()</span> </span>&#123;</div><div class="line">    mLuckyLanguage = mLuckyComponent.luckyLanguage();</div><div class="line">    mLuckyNumber = mLuckyComponent.luckyNumber();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    LuckyTest test = <span class="keyword">new</span> LuckyTest();</div><div class="line">    test.initInjector();</div><div class="line"></div><div class="line">    <span class="comment">// 二选一, 注入的方式看需求</span></div><div class="line">    test.separateInject();</div><div class="line">    test.overallInject();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以根据下图进行理解</p>
<p><img src="https://git.oschina.net/averson/Source/raw/master/dagger-1.png" alt=""></p>
<p><code>@Providers</code> 可以提供任何依赖, 当然也包括抽象, 那么如果同一抽象不同实现要如何区分呢 ?</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Qualifier</span></div><div class="line"><span class="meta">@Documented</span></div><div class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Woman &#123;&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Qualifier</span></div><div class="line"><span class="meta">@Documented</span></div><div class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Man &#123;&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Module</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClothesModule</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="meta">@Provides</span> <span class="meta">@Man</span> <span class="function">Clothes <span class="title">provideManClothes</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Clothes(<span class="string">"男装"</span>);</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="meta">@Provides</span> <span class="meta">@Woman</span> <span class="function">Clothes <span class="title">provideWomanClothes</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Clothes(<span class="string">"女装"</span>);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Component</span>(modules = ClothesModule.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ClothesComponent</span> </span>&#123;</div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">inject</span><span class="params">(Main main)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Inject</span> <span class="meta">@Man</span>   Clothes mManClothes;</div><div class="line">  <span class="meta">@Inject</span> <span class="meta">@Woman</span> Clothes mWomanClothes;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    Main main = <span class="keyword">new</span> Main();</div><div class="line">    main.inject();</div><div class="line">    System.out.println(main.mManClothes);</div><div class="line">    System.out.println(main.mWomanClothes);</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">inject</span><span class="params">()</span> </span>&#123;</div><div class="line">    DaggerClothesComponent.builder()</div><div class="line">      .clothesModule(<span class="keyword">new</span> ClothesModule())</div><div class="line">      .build()</div><div class="line">      .inject(<span class="keyword">this</span>);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>以上的 <code>@Man</code> 和 <code>@Woman</code> 为我们自己基于 <code>@Qualifier</code> 创建的注解, 用来在 <code>Module</code> 中标识区分抽象的实现依赖, 另外还有一种方法就是将 <code>@Man</code> 和 <code>@Woman</code> 替换成 @Named(“Man”) 和 @Named(“Woman”), 但是不推荐.</p>
<h2 id="为什么使用懒加载"><a href="#为什么使用懒加载" class="headerlink" title="为什么使用懒加载 ?"></a>为什么使用懒加载 ?</h2><p>在 <a href="#"><code>Dagger2</code> 基本使用</a> 代码中的 <code>3-2</code> 我们进行了分别注入依赖 (其实是手动获取注射器暴露的依赖进行手动赋值), 目的是用到的时候才注入, 那么有没有自动注入但是使用的时候才实例化依赖的办法? 答案是肯定的, 那就是使用 <code>Lazy&lt;T&gt;</code>, 当我们调用 <code>Lazy&lt;T&gt;.get()</code> 的时候依赖才会实例化. 举个例子, 当我们使用一个 <code>App</code> 需要用到 <code>SharePreference</code> 进行保存一些值的时候, 它需要用户进行输入且完成提交才使用到 <code>SharePreference</code>, 这个时候我们用 <code>Lazy&lt;T&gt;</code> 显然更节省资源.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LuckyTest</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Inject</span> Lazy&lt;String&gt; mLuckyLanguage;</div><div class="line">  LuckyComponent       mLuckyComponent;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">initInjector</span><span class="params">()</span> </span>&#123;</div><div class="line">    mLuckyComponent = DaggerLuckyComponent.builder()</div><div class="line">      .luckyModule(<span class="keyword">new</span> LuckyModule())</div><div class="line">      .build();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">overallInject</span><span class="params">()</span> </span>&#123;</div><div class="line">    mLuckyComponent.inject(<span class="keyword">this</span>);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    LuckyTest test = <span class="keyword">new</span> LuckyTest();</div><div class="line">    test.overallInject();</div><div class="line">    System.out.println(test.mLuckyLanguage.get());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="处理子类注入问题"><a href="#处理子类注入问题" class="headerlink" title="处理子类注入问题"></a>处理子类注入问题</h2><p><code>Dagger2</code> 的注入是强类型关联的, 父类无法注入到子类中, 常用的解决方法如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseActivity</span> </span>&#123;</div><div class="line">  <span class="meta">@Override</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</div><div class="line">    <span class="comment">// ......</span></div><div class="line">    setupActivityComponent(App.getAppComponent());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">setupActivityComponent</span><span class="params">(AppComponent component)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="深入-Component"><a href="#深入-Component" class="headerlink" title="深入 Component"></a>深入 Component</h2><p>在我们为应用划分模块的时候, 会依据功能提供不同的 <code>Component</code> 来进行对不同模块的依赖注入. 比如这样划分:</p>
<p>这个时候就需要使用 <code>Component Dependencies</code> 和 <code>SubComponent</code>.</p>
<p>首先引用 <code>StackOverFlow</code> 上对 <code>Dagger</code> 这<a href="http://stackoverflow.com/questions/29587130/dagger-2-subcomponents-vs-component-dependencies" target="_blank" rel="external">两种方式的使用建议</a>:</p>
<blockquote>
<p>Component Dependencies - Use this when:</p>
</blockquote>
<ul>
<li>you want to keep two components independent.</li>
<li>you want to explicitly show what dependencies from one component is used by the other</li>
</ul>
<blockquote>
<p>SubComponents - Use this when:</p>
</blockquote>
<ul>
<li>you want to keep two component cohesive</li>
<li>you may not care to explicitly show what dependencies from one component is used by the other.</li>
</ul>
<p>总结一下就是:</p>
<ul>
<li><strong>你想让两个组件各自保持独立且在使用过程中明确的显示两者之间的依赖关系</strong>, 这中情况建议使用 <code>Component Dependencies</code>.</li>
<li><strong>你想让两个组件内聚且你不关心两个组件之间的依赖关系</strong>, 这种情况建议使用 <code>SubComponent</code>.</li>
</ul>
<p>两者的区别是 <code>Module</code> 依赖的共享, <code>SubComponent</code> 可以访问 <code>ParentModule</code> 提供的所有依赖, 而 <code>Component Dependencies</code> 只能访问 <code>Component</code> 暴露的对象</p>
<p>接下来看使用方式</p>
<p><img src="https://git.oschina.net/averson/Source/raw/master/dagger-2.png" alt=""></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Module</span> <span class="class"><span class="keyword">class</span> <span class="title">AModule</span> </span>&#123;</div><div class="line">  <span class="comment">// if BComponent is expose to B we can get it, otherwise we can not get it.</span></div><div class="line">  <span class="meta">@Provides</span> <span class="function">A <span class="title">provideA</span><span class="params">(B b)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> A(b);</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Module</span> <span class="class"><span class="keyword">class</span> <span class="title">BModule</span> </span>&#123;</div><div class="line">  <span class="meta">@Provides</span> <span class="function">B <span class="title">provideB</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> B();</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Component</span>(modules = BModule.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BComponent</span> </span>&#123;</div><div class="line">  <span class="function">B <span class="title">b</span><span class="params">()</span></span>; <span class="comment">// if no expose B, AComponent can't expose A because A need B to finish the building.</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Component</span>(modules = AModule.class, dependencies = BComponent.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">AComponent</span> </span>&#123;</div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">inject</span><span class="params">(Target target)</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Target</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Inject</span> A mA;</div><div class="line"></div><div class="line">  <span class="keyword">private</span> B mB;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    Target target = <span class="keyword">new</span> Target();</div><div class="line">    target.inject();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inject</span><span class="params">()</span> </span>&#123;</div><div class="line">    BComponent bComponent = DaggerBComponent.builder()</div><div class="line">      .bModule(<span class="keyword">new</span> BModule())</div><div class="line">      .build();</div><div class="line">    <span class="comment">// BComponent can keep independent inject</span></div><div class="line">    <span class="keyword">this</span>.mB = bComponent.b();</div><div class="line">    System.out.println(mB);</div><div class="line"></div><div class="line">    DaggerAComponent.builder()</div><div class="line">      .aModule(<span class="keyword">new</span> AModule())</div><div class="line">      <span class="comment">// explicitly show two component dependency relationship</span></div><div class="line">      .bComponent(bComponent)</div><div class="line">      .build()</div><div class="line">      .inject(<span class="keyword">this</span>);</div><div class="line">    System.out.println(mA);</div><div class="line">    System.out.println(mA.getB());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><img src="https://git.oschina.net/averson/Source/raw/master/dagger-3.png" alt=""></p>
<blockquote>
<p><code>SubComponent</code> 的使用, 通常是将共享元素放于上层, <code>Component</code> 无法互相访问暴露的接口, 每个 <code>SubComponent</code> 可以从上层的 <code>Module</code> 获得的暴露的依赖, 生成的源码中其实就是从上层获取下层需要的依赖提供给下层.</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">DaggerAComponent</span> <span class="keyword">implements</span> <span class="title">AComponent</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="keyword">private</span> Provider&lt;A&gt; provideAProvider;</div><div class="line"></div><div class="line">  <span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">BComponentImpl</span> <span class="keyword">implements</span> <span class="title">BComponent</span> </span>&#123;</div><div class="line">      <span class="keyword">private</span> <span class="keyword">final</span> BModule bModule;</div><div class="line"></div><div class="line">      <span class="keyword">private</span> Provider&lt;B&gt; provideBProvider;</div><div class="line"></div><div class="line">      <span class="function"><span class="keyword">private</span> <span class="title">BComponentImpl</span><span class="params">(BModule bModule)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.bModule = Preconditions.checkNotNull(bModule);</div><div class="line">        initialize();</div><div class="line">      &#125;</div><div class="line"></div><div class="line">      <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</div><div class="line">      <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">// &gt;&gt;&gt;</span></div><div class="line">        <span class="keyword">this</span>.provideBProvider =</div><div class="line">            BModule_ProvideBFactory.create(bModule, DaggerAComponent.<span class="keyword">this</span>.provideAProvider);</div><div class="line">        <span class="comment">// &lt;&lt;&lt;</span></div><div class="line">      &#125;</div><div class="line"></div><div class="line">      <span class="meta">@Override</span></div><div class="line">      <span class="function"><span class="keyword">public</span> B <span class="title">b</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> provideBProvider.get();</div><div class="line">      &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Module</span> <span class="class"><span class="keyword">class</span> <span class="title">AModule</span> </span>&#123;</div><div class="line">  <span class="meta">@Provides</span> <span class="function">A <span class="title">provideA</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> A();</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Module</span> <span class="class"><span class="keyword">class</span> <span class="title">BModule</span> </span>&#123;</div><div class="line">  <span class="meta">@Provides</span> <span class="function">B <span class="title">provideB</span><span class="params">(A a)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> B(a);</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Component</span>(modules = &#123;AModule.class&#125;)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">AComponent</span> </span>&#123;</div><div class="line">  <span class="function">A <span class="title">a</span><span class="params">()</span></span>;</div><div class="line">  <span class="function">BComponent <span class="title">plus</span><span class="params">(BModule <span class="keyword">module</span>)</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Subcomponent</span>(modules = BModule.class)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BComponent</span> </span>&#123;</div><div class="line">  <span class="function">B <span class="title">b</span><span class="params">()</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Target</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    Target target = <span class="keyword">new</span> Target();</div><div class="line">    target.inject();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">inject</span><span class="params">()</span> </span>&#123;</div><div class="line">    AComponent aComponent = DaggerAComponent.builder()</div><div class="line">      .aModule(<span class="keyword">new</span> AModule())</div><div class="line">      .build();</div><div class="line">    System.out.println(aComponent.a());</div><div class="line"></div><div class="line">    BComponent bComponent = aComponent.plus(<span class="keyword">new</span> BModule());</div><div class="line">    B b = bComponent.b();</div><div class="line">    System.out.println(b);</div><div class="line">    System.out.println(b.getA());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="关于-Scope-的理解"><a href="#关于-Scope-的理解" class="headerlink" title="关于 Scope 的理解"></a>关于 Scope 的理解</h2><p>理解一个概念: <code>Scope</code> 仅仅只是一个标识便于注入范围的限定, 并不具备创建单例的功能.</p>
<p>实现真正意义上的周期范围内单例主要看两点:</p>
<ul>
<li>Component 之间的依赖关系</li>
<li>Inject 的位置</li>
</ul>
<p>比如 <code>AppComponent</code>( <code>@Singleton</code> ) 被 <code>UserComponent</code>( <code>@UserScope</code> ) 依赖, 且 <code>AppComponent</code> 初始化在 <code>Application</code> 而 <code>UserComponent</code> 初始化且注入位置在 <code>UserActivity</code> 中, 那么由于 <code>Application</code> 只初始化一次, <code>AppComponent</code> 提供的依赖自然也是单例, <code>UserActivity</code> 存活的周期内 <code>Application</code> 有且只有一个, 所以 <code>UserComponent</code> 从 <code>Application</code> 获取 <code>AppComponent</code> 协助进行注入依赖的过程中, <code>UserActivity</code> 注入的 <code>@Singleton</code> 依赖能在 <code>Application</code> 下的 <code>Activity</code> 生命周期内是单例, 即 <strong>局部单例</strong>.</p>
<p><code>Scope</code> 注解使得注入是单例的源码只是从普通的 <code>Provider</code> 换成了 <code>DoubleCheck</code>, 从而保证是单例.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">DoubleCheck</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Provider</span>&lt;<span class="title">T</span>&gt;, <span class="title">Lazy</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">  <span class="meta">@Override</span></div><div class="line">  <span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">()</span> </span>&#123;</div><div class="line">    Object result = instance;</div><div class="line">    <span class="keyword">if</span> (result == UNINITIALIZED) &#123;</div><div class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</div><div class="line">        result = instance;</div><div class="line">        <span class="keyword">if</span> (result == UNINITIALIZED) &#123;</div><div class="line">          result = provider.get();</div><div class="line">          Object currentInstance = instance;</div><div class="line">          instance = result;</div><div class="line">          provider = <span class="keyword">null</span>;</div><div class="line">        &#125;</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> (T) result;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>Scope</code> 实践的参考代码在参考文献作者的 <code>Github</code> 上已经提供了非常好的<a href="https://github.com/frogermcs/Dagger2Recipes-UserScope" target="_blank" rel="external">案例</a>, 就不贴代码占用文章篇幅了, 值给出类似的个人理解图.</p>
<p><img src="https://git.oschina.net/averson/Source/raw/master/dagger-4.png" alt=""></p>
<ul>
<li><p><code>Scope</code> 使用的注意事项</p>
<ul>
<li><code>Component</code> 之间依赖时, 父类有 <code>Scope</code> 时子类必须也要有 <code>Scope</code>, 且子类 <code>Scope</code> 必须小于父类 <code>Scope</code>, 很好理解就范围划分</li>
<li><code>Module</code> 对提供的依赖有 <code>Scope</code> 注解, <code>Component</code> 也必须有一致的 <code>Scope</code>, 但是 <code>Module</code> 提供依赖没有 <code>Scope</code> 注解, 则 <code>Component</code> 有无 <code>Scope</code> 都均没关系.</li>
<li><code>Scope</code> 对于 <code>Module</code> 只能使用在方法上, 对于 <code>Component</code> 使用在接口上.</li>
</ul>
<h2 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h2><p><a href="http://frogermcs.github.io/" target="_blank" rel="external">froger_mcs dev blog dagger2 series</a><br><a href="https://github.com/googlesamples/android-architecture/tree/todo-mvp-dagger/" target="_blank" rel="external">建议阅读 google mvp with Dagger</a></p>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/01/14/hello-world/" rel="next" title="Averson">
                <i class="fa fa-chevron-left"></i> Averson
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/02/23/静态工厂 & 构造器/" rel="prev" title="静态工厂 & 构造器">
                静态工厂 & 构造器 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/02/14/Dagger2 浅析/"
           data-title="Dagger2 浅析" data-url="http://jocens.oschina.io/blog/blog/2017/02/14/Dagger2 浅析/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目錄
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            本站概覽
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.gif"
               alt="Averson" />
          <p class="site-author-name" itemprop="name">Averson</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">文章</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">標籤</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#QA"><span class="nav-number">1.</span> <span class="nav-text">QA</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是-IOC-为什么使用-IOC"><span class="nav-number">2.</span> <span class="nav-text">什么是 IOC ? 为什么使用 IOC ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么使用-Dagger2"><span class="nav-number">3.</span> <span class="nav-text">为什么使用 Dagger2 ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dagger2-有哪些基本操作符"><span class="nav-number">4.</span> <span class="nav-text">Dagger2 有哪些基本操作符?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dagger2-基本使用"><span class="nav-number">5.</span> <span class="nav-text">Dagger2 基本使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么使用懒加载"><span class="nav-number">6.</span> <span class="nav-text">为什么使用懒加载 ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#处理子类注入问题"><span class="nav-number">7.</span> <span class="nav-text">处理子类注入问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#深入-Component"><span class="nav-number">8.</span> <span class="nav-text">深入 Component</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于-Scope-的理解"><span class="nav-number">9.</span> <span class="nav-text">关于 Scope 的理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文献"><span class="nav-number">10.</span> <span class="nav-text">参考文献</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Averson</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 強力驅動
</div>

<div class="theme-info">
  主題 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"averson"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/blog/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/blog/js/src/hook-duoshuo.js"></script>
  













  
  

  

  

  

  


</body>
</html>
